require '../lib/content'
require '../lib/dictionary'
require '../lib/vector'

# A cache is composed of a Dictionary and a set of
# Documents. This class provides a way to permanently
# store and also retrieve previously saved documents.

class Cache
  attr_reader :dictionary, :documents, :cache_file

  def initialize(cache_file)
    @dictionary, @documents = Cache.load_cache(cache_file)
    @dictionary = Dictionary.new if @dictionary.nil?
    @documents = {} if @documents.nil?
    @cache_file = cache_file
  end
  
  def add_document(document)
    vector = Vector.new
    document.extract_words do |word|
      word_index = @dictionary.add_word(word)
      vector.add_word_index(word_index) if word_index   
    end
    @documents[document.identifire] = vector
  end
  
  def add_documents(documents)
    documents.each { |doc| add_document(doc)}
  end
  
  def delete_document(identifier)
    doc = @documents.detect {|k,v| k == identifier}
    @documents.delete(doc[0]) unless doc.nil?
  end

  def dump
    File.open(@cache_file, "w") do |file|
      Marshal.dump(@dictionary, file)
      Marshal.dump(@documents, file)
    end
  end

  private 
  def Cache.load_cache(cache_file)
    dictionary = Dictionary.new
    documents = {}
    
    begin
      File.open(cache_file, "r") do |file| 
        dictionary = Marshal.load(file)
        documents  = Marshal.load(file)
      end
    rescue
      ;
    end
  
    [dictionary, documents]
  end

end